package org.idansof.otp.ui;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.idansof.otp.client.Itinerary;
import org.idansof.otp.client.Leg;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class DisplayLegsFragment extends Fragment {
	
	private Itinerary itinerary;
	
	@Override
	public View onCreateView(LayoutInflater vi, ViewGroup container,
			Bundle savedInstanceState) {
		
		itinerary = (Itinerary) getArguments().get("itinerary");
		List<Leg> legs = itinerary.getLegs();
        View convertView = vi.inflate(R.layout.plan_leg, null);
		
        TableLayout legTable = (TableLayout) convertView.findViewById(R.id.plan_leg_table);
        for(Leg leg : legs)
        {
        	TableRow row = new TableRow(getActivity());
        	ImageView methodIcon = new ImageView(getActivity());
        	TextView textTo = new TextView(getActivity());
        	TextView textDuration = new TextView(getActivity());
        	TextView textDistance = new TextView(getActivity());
        	
        	switch(leg.getMode())
        	{
        	case WALK:
            	textTo.setText(leg.getTo().getAddress());
        		break;			        	
        	default:
    	        textTo.setText(leg.getRoute() + "\n"+leg.getTo().getAddress());
        			
        	}
        	String methodIconPath = "leg/mode/"+leg.getMode().toString().toLowerCase()+".png";
        	try {
				Drawable methodIconImage = Drawable.createFromStream(getResources().getAssets().open(methodIconPath), methodIconPath);
				methodIcon.setImageDrawable(methodIconImage);
			} catch (IOException e) {
				Log.e(getClass().toString(), "Cannot load icon for "+leg.getMode(),e );
			}
        	textDuration.setText(((int) (leg.getDuration()/1000/60)) + " "+getString(R.string.itinerary_minutes));
        	textDistance.setText(Integer.toString((int) leg.getDistance()) + " "+getString(R.string.length_unit));
        	
        	if (Locale.getDefault().getISO3Language().equals("heb") || Locale.getDefault().getISO3Language().equals("ara"))
        	{
        		// RTL Languages
	        	row.addView(textDistance);
	        	row.addView(textDuration);
	        	row.addView(textTo);
	        	row.addView(methodIcon);
        	}
        	else
        	{
	        	row.addView(methodIcon);
	        	row.addView(textTo);
	        	row.addView(textDuration);
	        	row.addView(textDistance);
        		
        	}
        	
        	for(int i = 0; i < row.getVirtualChildCount(); i++){
        	    row.getVirtualChildAt(i).setPadding(5,5,5,5);
        	}
        	
        	legTable.addView(row);
        }
        return convertView;
	}
	

}
